import type { Router, RouteRecordRaw } from "vue-router";
import { useToken } from "@/components/windows/hooks/use-token";

const globalRouter = ref<Router | null>(null);
// 默认路由配置
const defaultRouter: Readonly<RouteRecordRaw[]> = [
  {
    path: "/windows",
    name: "windows",
    component: () => import("@/components/windows/Index.vue"),
    meta: { title: "圆环之理" },
    children: []
  },
  {
    path: "/windows/login",
    component: () => import("@/components/windows/views/login/Index.vue")
  }
];

export const toLogin = (to, next) => {
  // 白名单配置（不需要登录的路由）
  const whiteList = ["/windows/login", "/windows/register"];

  // 获取Token状态
  const hasToken = useToken().getToken();
  if (hasToken) {
    // 已登录时访问登录页 → 重定向到首页
    to.path === "/windows/login" ? next("/") : next();
    return;
  }
  // 未登录时访问需要认证的页面 → 跳转登录
  if (!whiteList.includes(to.path)) {
    next(`/windows/login?redirect=${encodeURIComponent(to.fullPath)}`);
    return;
  }
  next(); // 放行白名单路由
}

// 提供合并后的路由配置
export const provideRouter = (router: Router) => {
  globalRouter.value = router;
  defaultRouter.forEach(route => router.addRoute(route));
  router.beforeEach((to, from, next) => {
    toLogin(to, next);
  });

};
